package com.doucat.support.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;

import androidx.appcompat.widget.AppCompatImageView;

import com.tonly.doucatlibrary.R;

/**
 * -----------------------------------------------------------------
 * Copyright (C) 2021-2031, by tonly, All rights reserved.
 * -----------------------------------------------------------------
 * File: WrapWidthProgress.java
 * Author: wangfy
 * Create: 2021/7/13 9:36
 *
 * 排行榜进度条
 * 与Progress不同，Progress会绘制max对应的宽度
 *
 * 排行榜进度条只绘制到progress处
 *
 * 在一组排行榜中，存在最大值，并需要定义最大的宽度，
 * 但是不必绘制完最大的宽度，而是根据当前的progress绘制对应比例的宽度
 */
public class WrapProgress extends AppCompatImageView {
    private String TAG="WrapWidthProgress";
    /**
     * max对应的宽度，没有实际意义
     * 用来计算progress应该绘制多宽
     * 也因此，android:layout_width的值意义是不大的，
     * 因此，onMeasure覆盖了width
     * 在布局中直接使用android:layout_width="wrap_content"即可
     */
    private int data_width;
    private int type;
    //横着用来做排行榜
    public static final int HORIZONTAL = 0;
    //竖着的适合做条形统计图
    public static final int VERTICAL = 1;
    public WrapProgress(Context context) {
        this(context, null);
    }

    public WrapProgress(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WrapProgress(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WrapProgress, defStyleAttr, 0);
        data_width = a.getDimensionPixelSize(R.styleable.WrapProgress_data_width, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                16, getResources().getDisplayMetrics()));
        //默认横着的
        type= a.getInt(R.styleable.WrapProgress_android_orientation,HORIZONTAL);
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int heightSize=0;
        int widthSize=0;
        if(type==HORIZONTAL){
            heightSize = MeasureSpec.getSize(heightMeasureSpec);
            widthSize= data_width *progress/max;
        }else  if(type==VERTICAL){
            heightSize = data_width *progress/max;
            widthSize= MeasureSpec.getSize(widthMeasureSpec);
        }
        setMeasuredDimension(widthSize,heightSize);
    }

    private int progress;
    private int max;

    public void setValue(int max,int value){
        this.max=max;
        this.progress=value;
        invalidate();
        requestLayout();
    }

    public void setProgress(int value){
        this.progress=value;
        invalidate();
        requestLayout();
    }

    public void setMax(int max) {
        this.max = max;
        invalidate();
        requestLayout();
    }
}